<template>
  <div class="edit-container">
    <Toolbar
      class="edit-container-tool"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{ height: height }"
      style="overflow-y: hidden; width: 100%"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '500px'
  }
})
const emits = defineEmits(['update:content'])
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 编辑器类型
const mode = ref('default')
// 内容 HTML
const valueHtml = ref('')
// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.content
  }, 500)
})
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...', autoFocus: false  }
// 输入内容
const handleChange = (event) => {
  emits('update:content', event.getHtml())
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 创建实例
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>
<style lang="scss" scoped>
.edit-container {
  border: 1px solid #dcdee2;
  &-tool {
    border-bottom: 1px solid #dcdee2;
    padding: 4px 0px;
  }
}
</style>
